package com.atguigu.champter7.state;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.FunctionInitializationContext;
import org.apache.flink.runtime.state.FunctionSnapshotContext;
import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.ArrayList;

public class Flink01_Operator_State_ListSate {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("reset.port",9999);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        env.enableCheckpointing(3000);// 开启checkpoint, 周期是3000ms. 默认checkpoint的地址: JobManager的内存


        env
                .socketTextStream("hadoop104",9999)
                .flatMap(new MyFlatMap(){})
                .print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class MyFlatMap implements FlatMapFunction<String,String>, CheckpointedFunction {
        ArrayList<String> words = new ArrayList<>();
        private ListState<String> listState;
        @Override
        public void flatMap(String value, Collector<String> out) throws Exception {
            String[] data = value.split(" ");
            for (String word : data) {
                words.add(word);
            }
            out.collect(words.toString());
            if (value.contains("x")){
                throw new RuntimeException("自杀小队");
            }
        }

        @Override
        // 把状态保存起来
        // 每个并行度都会周期性的执行, 把数据周期性的保存到状态中
        public void snapshotState(FunctionSnapshotContext ctx) throws Exception {
            listState.update(words);// 是先删除, 再新增
        }

        @Override
        // 初始状态: 当程序恢复的时候, 从状态中读取数据恢复
        // 程序启动的时候, 每个并行度执行一次
        public void initializeState(FunctionInitializationContext ctx) throws Exception {
             listState = ctx.getOperatorStateStore().getListState(new ListStateDescriptor<String>("list", String.class));
            Iterable<String> it = listState.get();
            for (String s : it) {
                words.add(s);
            }
        }
    }
}
